import {RemoteStorage} from "./storage";
import fs from "fs";
import logging from '../logging'
import {skipDownload} from './skip'

// download oss object to localPath.
export async function download(remoteStorage: RemoteStorage, objectKey: string, localPath: string): Promise<void> {
    const existed = await remoteStorage.stat(objectKey);
    if (!existed){
        logging.infoV1(`oss object ${objectKey} does not exist, skip`);
        return;
    }

    const result = await remoteStorage.get(objectKey, localPath)
    if (result.res.status == 200) {
        logging.infoV1(`download file ${objectKey} successfully`);
    } else {
        logging.errorV1(`failed to download file ${objectKey}`);
    }
}

// will download only when the remote file is newer
export async function downloadWithUpdate(remoteStorage: RemoteStorage, objectKey: string, localPath: string, localModifiedTime: Date):Promise<void>{
    const existed =  await remoteStorage.stat(objectKey);
    if (!existed){
        logging.infoV1(`oss object ${objectKey} does not exist, skip`);
        return;
    }

    const skip = await skipDownload(remoteStorage, objectKey, localModifiedTime);
    if (skip){
        logging.infoV1(`skip download file ${objectKey}`);
        return;
    }

    const result = await remoteStorage.get(objectKey, localPath)
    if (result.res.status == 200) {
        logging.infoV1(`download file ${objectKey} successfully`);
    } else {
        logging.errorV1(`failed to download file ${objectKey}`);
    }

}



